﻿#include "modeltreewidget.h"
#include <QHeaderView>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>

#include "vtkSphereSource.h"
#include "vtkCubeSource.h"
#include "vtkCylinderSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"

ModelTreeWidget::ModelTreeWidget(QWidget* parent)
    : QTreeWidget(parent),
    m_blockSelectionSync(false)
{
    setupUI();
    setupConnections();
}

ModelTreeWidget::~ModelTreeWidget()
{
}

void ModelTreeWidget::setupUI()
{
    setHeaderLabel("对象列表");
    setHeaderHidden(false);
    setMinimumWidth(200);

    // 设置根节点
    QTreeWidgetItem* root = new QTreeWidgetItem(this, QStringList() << "模型");
    root->setExpanded(true);

    // 设置子节点
    QTreeWidgetItem* sphereItem = new QTreeWidgetItem(root, QStringList() << "球体");
    sphereItem->setData(0, ActorModeRole, static_cast<int>(PickMode::VOLUME));
    QTreeWidgetItem* cubeItem = new QTreeWidgetItem(root, QStringList() << "立方体");

    setSelectionMode(QAbstractItemView::SingleSelection);
    setContextMenuPolicy(Qt::CustomContextMenu);
}

void ModelTreeWidget::setupConnections()
{
    connect(this, &QTreeWidget::itemClicked,
            this, &ModelTreeWidget::onItemClicked);
    connect(this, &QTreeWidget::itemSelectionChanged,
            this, &ModelTreeWidget::onItemSelectionChanged);
}

void ModelTreeWidget::setManagers(std::shared_ptr<SelectionManager> highlightManager,
                                  std::shared_ptr<ActorManager> actorManager,
                                  vtkSmartPointer<MyVtkInteractorSelect> interactorStyle)
{
    m_highlightManager = highlightManager;
    m_actorManager = actorManager;
    m_interactorStyle = interactorStyle;

    // 设置选择更改回调
    if(m_interactorStyle)
    {
        m_interactorStyle->SetSelectionChangedCallback([this]()
                                                       {
                                                           syncSelectionFromVTK();
                                                       });
    }

    updateTree();
}

void ModelTreeWidget::updateTree()
{
    clear();
    if(!m_actorManager) return;

    // 添加分类根节点
    QTreeWidgetItem* volumeRoot = new QTreeWidgetItem(this, QStringList() << QString("体对象 (%1)").arg(m_actorManager->GetActorCount(PickMode::VOLUME)));
    QTreeWidgetItem* faceRoot = new QTreeWidgetItem(this, QStringList() << QString("面对象 (%1)").arg(m_actorManager->GetActorCount(PickMode::FACE)));
    QTreeWidgetItem* edgeRoot = new QTreeWidgetItem(this, QStringList() << QString("边对象 (%1)").arg(m_actorManager->GetActorCount(PickMode::EDGE)));
    QTreeWidgetItem* pointRoot = new QTreeWidgetItem(this, QStringList() << QString("点对象 (%1)").arg(m_actorManager->GetActorCount(PickMode::POINT)));

    volumeRoot->setExpanded(true);
    faceRoot->setExpanded(true);
    edgeRoot->setExpanded(true);
    pointRoot->setExpanded(true);

    // 设置分类节点的数据
    volumeRoot->setData(0, ActorModeRole, static_cast<int>(PickMode::VOLUME));
    faceRoot->setData(0, ActorModeRole, static_cast<int>(PickMode::FACE));
    edgeRoot->setData(0, ActorModeRole, static_cast<int>(PickMode::EDGE));
    pointRoot->setData(0, ActorModeRole, static_cast<int>(PickMode::POINT));

    // 获取所有Actor并添加到对应分类
    auto allActors = m_actorManager->GetAllActors();
    for(vtkActor* actor : allActors)
    {
        auto info = m_actorManager->GetActorInfo(actor);
        QString displayName = QString::fromStdString(info.name);

        QTreeWidgetItem* parent = nullptr;
        switch(info.mode)
        {
        case PickMode::VOLUME: parent = volumeRoot; break;
        case PickMode::FACE: parent = faceRoot; break;
        case PickMode::EDGE: parent = edgeRoot; break;
        case PickMode::POINT: parent = pointRoot; break;
        }

        if(parent)
        {
            QTreeWidgetItem* item = new QTreeWidgetItem(parent, QStringList() << displayName);
            item->setData(0, ActorPointerRole, QVariant::fromValue<void*>(actor));
            item->setData(0, ActorModeRole, static_cast<int>(info.mode));

            // 根据高亮状态设置外观
            bool isHighlighted = m_highlightManager ? m_highlightManager->IsActorHighlighted(actor) : false;
            updateItemAppearance(item, isHighlighted);
        }
    }

    // 更新分类节点的计数显示
    volumeRoot->setText(0, QString("体对象 (%1)").arg(volumeRoot->childCount()));
    faceRoot->setText(0, QString("面对象 (%1)").arg(faceRoot->childCount()));
    edgeRoot->setText(0, QString("边对象 (%1)").arg(edgeRoot->childCount()));
    pointRoot->setText(0, QString("点对象 (%1)").arg(pointRoot->childCount()));

    // 发出对象数量变化信号
    emit objectCountChanged(allActors.size());
}

void ModelTreeWidget::syncSelectionFromVTK()
{
    if(m_blockSelectionSync || !m_highlightManager) return;

    m_blockSelectionSync = true;

    // 清除树形控件的选择
    clearSelection();

    // 获取高亮的Actor
    auto highlightedActors = m_highlightManager->GetSelectedActors();

    // 在树形控件中选中对应的项
    for(vtkActor* actor : highlightedActors)
    {
        QTreeWidgetItem* item = findTreeItemByActor(actor);
        if(item)
        {
            item->setSelected(true);
            // 确保父项展开以便看到选中的项
            if(item->parent())
            {
                item->parent()->setExpanded(true);
            }
        }
    }

    // 更新所有项的外观
    QTreeWidgetItemIterator it(this);
    while(*it)
    {
        QTreeWidgetItem* item = *it;
        if(item->childCount() == 0)
        { // 只处理叶子节点
            void* actorPtr = item->data(0, ActorPointerRole).value<void*>();
            vtkActor* actor = static_cast<vtkActor*>(actorPtr);
            if(actor)
            {
                bool isHighlighted = m_highlightManager->IsActorHighlighted(actor);
                updateItemAppearance(item, isHighlighted);
            }
        }
        ++it;
    }

    m_blockSelectionSync = false;
}

void ModelTreeWidget::syncSelectionToVTK()
{
    if(m_blockSelectionSync || !m_interactorStyle || !m_highlightManager) return;

    // 获取树形控件中选中的项
    QList<QTreeWidgetItem*> selectedItems = this->selectedItems();

    // 获取当前是否是多选模式
    bool multiPick = m_interactorStyle->GetMultiPickMode();

    if(!multiPick && selectedItems.size() > 1)
    {
        // 单选模式下只保留最后一个选择
        for(int i = 0; i < selectedItems.size() - 1; ++i)
        {
            selectedItems[i]->setSelected(false);
        }
        selectedItems = this->selectedItems();
    }

    // 清除当前高亮（如果不是多选模式）
    if(!multiPick)
    {
        m_highlightManager->ClearAllSelectedActors();
    }

    // 处理每个选中的项
    for(QTreeWidgetItem* item : selectedItems)
    {
        if(item->childCount() == 0)
        { // 只处理叶子节点
            void* actorPtr = item->data(0, ActorPointerRole).value<void*>();
            vtkActor* actor = static_cast<vtkActor*>(actorPtr);

            if(actor)
            {
                if(m_highlightManager->IsActorHighlighted(actor))
                {
                    // 如果已经高亮，在多选模式下取消选择
                    if(multiPick)
                    {
                        m_highlightManager->RemoveSeletedActor(actor);
                    }
                }
                else
                {
                    // 添加高亮
                    PickMode mode = static_cast<PickMode>(item->data(0, ActorModeRole).toInt());
                    m_highlightManager->AddSelectedActor(actor, mode);
                }
            }
        }
    }

    // 请求渲染
    emit requestRender();

    // 更新树形控件显示
    updateTree();
}

QTreeWidgetItem* ModelTreeWidget::findTreeItemByActor(vtkActor* actor)
{
    QTreeWidgetItemIterator it(this);
    while(*it)
    {
        QTreeWidgetItem* item = *it;
        if(item->childCount() == 0)
        { // 只处理叶子节点
            void* actorPtr = item->data(0, ActorPointerRole).value<void*>();
            if(static_cast<vtkActor*>(actorPtr) == actor)
            {
                return item;
            }
        }
        ++it;
    }
    return nullptr;
}

void ModelTreeWidget::updateItemAppearance(QTreeWidgetItem* item, bool isHighlighted)
{
    if(isHighlighted)
    {
        item->setBackground(0, QBrush(QColor(255, 255, 0, 100))); // 黄色背景
        item->setForeground(0, QBrush(Qt::black)); // 黑色文字
        QFont font = item->font(0);
        font.setBold(true);
        item->setFont(0, font);
    }
    else
    {
        item->setBackground(0, QBrush()); // 恢复默认背景
        item->setForeground(0, QBrush()); // 恢复默认文字颜色
        QFont font = item->font(0);
        font.setBold(false);
        item->setFont(0, font);
    }
}

void ModelTreeWidget::onItemClicked(QTreeWidgetItem* item, int column)
{
    Q_UNUSED(column);

    if(!item || item->childCount() > 0)
    {
        return; // 点击的是根节点，忽略
    }

    m_blockSelectionSync = true;
    syncSelectionToVTK();
    m_blockSelectionSync = false;
}

void ModelTreeWidget::onItemSelectionChanged()
{
    if(m_blockSelectionSync) return;

    syncSelectionToVTK();
}



void ModelTreeWidget::onDeleteSelected()
{
    if(!m_highlightManager || !m_actorManager) return;

    auto highlightedActors = m_highlightManager->GetSelectedActors();

    if(highlightedActors.empty())
    {
        QMessageBox::information(this, "提示", "没有选中的对象可删除");
        return;
    }

    // 从管理器中移除并删除Actor
    for(vtkActor* actor : highlightedActors)
    {
        m_actorManager->RemoveActor(actor);
        // 注意：在实际应用中，您可能需要从渲染器中移除actor
        // 这取决于您的架构设计
    }

    m_highlightManager->ClearAllSelectedActors();

    emit requestRender();
    updateTree();
}

void ModelTreeWidget::onClearAll()
{
    if(!m_actorManager) return;

    // 获取所有Actor
    auto allActors = m_actorManager->GetAllActors();

    if(allActors.empty())
    {
        QMessageBox::information(this, "提示", "没有可清空的对象");
        return;
    }

    // 清空管理器
    // 注意：在实际应用中，您需要根据您的架构来清空Actor
    // 这里假设ActorManager有清空所有Actor的方法
    // 如果没有，您可能需要重置管理器

    if(m_highlightManager)
    {
        m_highlightManager->ClearAllSelectedActors();
    }

    emit requestRender();
    updateTree();
}

void ModelTreeWidget::onMultiPickToggled(bool enabled)
{
}

void ModelTreeWidget::onPickModeChanged()
{
}

void ModelTreeWidget::contextMenuEvent(QContextMenuEvent* event)
{
    QTreeWidgetItem* item = itemAt(event->pos());

    // 如果点击的是空白区域，显示完整的上下文菜单
    // 如果点击的是具体对象，可以显示特定于对象的菜单
    if(item && item->childCount() == 0)
    {
        // 对象特定的上下文菜单
        QMenu objectMenu(this);
        objectMenu.addAction(m_actionDeleteSelected);
        objectMenu.exec(event->globalPos());
    }
    else
    {
        // 全局上下文菜单
        m_contextMenu->exec(event->globalPos());
    }
}